package com.jxdinfo.hussar.cloud.module.example.tjjc.towerdatahistory.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towercrane.dao.TowerCraneMapper;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towercrane.model.TowerCrane;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerdatahistory.dao.TowerDataHistoryMapper;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerdatahistory.model.TowerDataHistory;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerdatahistory.service.TowerDataHistoryService;
import com.jxdinfo.hussar.cloud.module.example.tjjc.towerdatahistory.vo.*;
import com.jxdinfo.hussar.cloud.module.example.tjjc.util.DateHandleUtil;
import com.jxdinfo.hussar.platform.core.base.apiresult.ApiResponse;
import com.jxdinfo.hussar.platform.core.utils.BeanUtil;
import com.jxdinfo.hussar.support.datasource.annotations.HussarDs;
import com.jxdinfo.hussar.support.mp.base.service.impl.HussarServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 塔机历史数据服务实现类
 */
@Service("tjjc.towerdatahistory.TowerDataHistoryServiceImpl")
@HussarDs("master")
public class TowerDataHistoryServiceImpl extends HussarServiceImpl<TowerDataHistoryMapper, TowerDataHistory> implements TowerDataHistoryService {

    private static final Logger logger = LoggerFactory.getLogger(TowerDataHistoryServiceImpl.class);

    private static final String RETURN_CODE = "0";

    @Autowired
    private TowerDataHistoryMapper towerDataHistoryMapper;
    @Autowired
    private TowerCraneMapper towerCraneMapper;

    @Override
    public ApiResponse<TowerDataHistoryPageVO> findByPage(TowerDataHistorySearchVO towerDataHistorySearchVO) {
        QueryWrapper<TowerDataHistory> wrapper = new QueryWrapper();
        Page<TowerDataHistory> page = new Page<>();
        page.setPages(towerDataHistorySearchVO.getPage());
        page.setSize(towerDataHistorySearchVO.getRows());

        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTowerId())) {
            wrapper.eq("tower_id", towerDataHistorySearchVO.getTowerId());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getDataType())) {
            wrapper.eq("data_type", towerDataHistorySearchVO.getDataType());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", towerDataHistorySearchVO.getTyProjectCode());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeStart())) {
            wrapper.ge("collection_time", towerDataHistorySearchVO.getCollectionTimeStart());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeEnd())) {
            Date endTime = DateUtil.endOfDay(towerDataHistorySearchVO.getCollectionTimeEnd());
            wrapper.le("collection_time", endTime);
        }

        wrapper.orderByDesc("collection_time");

        Page<TowerDataHistory> historyPage = towerDataHistoryMapper.selectPage(page, wrapper);
        TowerDataHistoryPageVO towerDataHistoryPageVO = new TowerDataHistoryPageVO();
        towerDataHistoryPageVO.setCount(historyPage.getTotal());
        towerDataHistoryPageVO.setData(historyPage.getRecords());
        towerDataHistoryPageVO.setCode(RETURN_CODE);

        if(towerDataHistoryPageVO.getCount() > 0) {

            //todo 没有获取设备信息service
            //Map<String, DeviceInfoDto> deviceInfoDtoMap = deviceService.findDeviceAndLocationByProductType(DeviceTypeEnum.DEVICE_TYPE_TOWER, towerDataHistorySearchDto.getTyProjectCode());

            QueryWrapper<TowerCrane> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ty_project_code", towerDataHistorySearchVO.getTyProjectCode());
            List<TowerCrane> towers = towerCraneMapper.selectList(queryWrapper);
            Map<String, String> map = towers.stream().collect(Collectors.toMap(TowerCrane::getId, TowerCrane::getTowerName));
            for(TowerDataHistory towerDataHistory : towerDataHistoryPageVO.getData()) {
                towerDataHistory.setTowerName(map.get(towerDataHistory.getTowerId()));

                //todo 没有获取设备信息service
                TowerCrane tower = towerCraneMapper.selectById(towerDataHistory.getTowerId());
//                DeviceInfoDto towerDeviceInfoDto = deviceInfoDtoMap.get(tower.getDeviceCode());
//                //获取设备状态重新赋值
//                if (towerDeviceInfoDto != null) {
//                    if(towerDeviceInfoDto.getOnlineStatus()==0){
//                        towerDataHistory.setDeviceStatus(2);
//                    }else if(towerDeviceInfoDto.getOnlineStatus()==1){
//                        towerDataHistory.setDeviceStatus(0);
//                    }
//                }else{
//                    towerDataHistory.setDeviceStatus(2);
//                }
            }
        }

        return ApiResponse.success(towerDataHistoryPageVO);
    }

    @Override
    public ApiResponse<List<TowerDataHistoryVO>> findLineChart(TowerDataHistorySearchVO towerDataHistorySearchVO) {
        QueryWrapper<TowerDataHistory> wrapper = new QueryWrapper<>();

        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTowerId())) {
            wrapper.eq("tower_id", towerDataHistorySearchVO.getTowerId());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getDataType())) {
            wrapper.eq("data_type", towerDataHistorySearchVO.getDataType());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", towerDataHistorySearchVO.getTyProjectCode());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeStart())) {
            wrapper.ge("collection_time", towerDataHistorySearchVO.getCollectionTimeStart());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeEnd())) {
//            towerDataHistoryPageQueryVO.setCollectionTimeEnd(DateUtils.nDaysAfter(1, towerDataHistoryPageQueryVO.getCollectionTimeEnd()));
            wrapper.lt("collection_time", towerDataHistorySearchVO.getCollectionTimeEnd());
        }

        wrapper.orderByDesc("collection_time");

        List<TowerDataHistory> towerDataHistoryList = towerDataHistoryMapper.selectList(wrapper);

        List<TowerDataHistoryVO> towerDataHistoryVOS = BeanUtil.copyToList(towerDataHistoryList, TowerDataHistoryVO.class);

        for (TowerDataHistoryVO towerDataHistoryVO : towerDataHistoryVOS) {
            towerDataHistoryVO.setTime(towerDataHistoryVO.getCollectionTime().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        }

        return ApiResponse.success(towerDataHistoryVOS);
    }

    @Override
    public ApiResponse<List<TowerDataHistoryVO>> findByList(TowerDataHistorySearchVO towerDataHistorySearchVO) {
        QueryWrapper<TowerDataHistory> wrapper = new QueryWrapper<>();

        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTowerId())) {
            wrapper.eq("tower_id", towerDataHistorySearchVO.getTowerId());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getDataType())) {
            wrapper.eq("data_type", towerDataHistorySearchVO.getDataType());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", towerDataHistorySearchVO.getTyProjectCode());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeStart())) {
            wrapper.ge("collection_time", towerDataHistorySearchVO.getCollectionTimeStart());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeEnd())) {
            Date endTime = DateUtil.endOfDay(towerDataHistorySearchVO.getCollectionTimeEnd());
            wrapper.le("collection_time", endTime);
        }

        wrapper.orderByDesc("collection_time");

        List<TowerDataHistory> list = towerDataHistoryMapper.selectList(wrapper);

        List<TowerDataHistoryVO> towerDataHistoryVOS = BeanUtil.copyToList(list, TowerDataHistoryVO.class);

        return ApiResponse.success(towerDataHistoryVOS);
    }

    @Override
    public ApiResponse<List<TowerDataHistoryLineVO>> findByLine(TowerDataHistorySearchVO towerDataHistorySearchVO) {
        QueryWrapper<TowerDataHistory> wrapper = new QueryWrapper<>();

        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTowerId())) {
            wrapper.eq("tower_id", towerDataHistorySearchVO.getTowerId());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getTyProjectCode())) {
            wrapper.eq("ty_project_code", towerDataHistorySearchVO.getTyProjectCode());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeStart())) {
            wrapper.ge("collection_time", towerDataHistorySearchVO.getCollectionTimeStart());
        }
        if(ObjectUtils.isNotEmpty(towerDataHistorySearchVO.getCollectionTimeEnd())) {
            Date endTime = DateUtil.endOfDay(towerDataHistorySearchVO.getCollectionTimeEnd());
            wrapper.le("collection_time", endTime);
        }

        wrapper.orderByAsc("collection_time");

        List<TowerDataHistory> list = towerDataHistoryMapper.selectList(wrapper);

        Map<String, List<TowerDataHistory>> map = list.stream().collect(Collectors.groupingBy(data -> data.getCollectionTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));

        List<TowerDataHistoryLineVO> dataList = new ArrayList<>();

        List<String> datetimeList = DateHandleUtil.completionDateList(towerDataHistorySearchVO.getCollectionTimeStart(), towerDataHistorySearchVO.getCollectionTimeEnd(), map.keySet());


        List<TowerCheckItemVO> checkItemList = towerCheckItemDtos();

        for(String datetimeStr : datetimeList) {

            TowerDataHistoryLineVO lineDto = new TowerDataHistoryLineVO();
            lineDto.setCollectionTime(datetimeStr);

            List<TowerDataHistoryVO> dataHistoryDtoList = new ArrayList<>();
            if(map.containsKey(datetimeStr)){
                List<TowerDataHistory> dataHistories = map.get(datetimeStr);
                Map<Integer, Double> dataMap = dataHistories.stream().collect(Collectors.toMap(TowerDataHistory::getDataType, TowerDataHistory::getMeasureValue));

                for(TowerCheckItemVO checkItem : checkItemList) {
                    TowerDataHistoryVO dataHistoryDto = new TowerDataHistoryVO();
                    dataHistoryDto.setCheckItemName(checkItem.getCheckName());
                    if(dataMap.containsKey(checkItem.getId())){
                        dataHistoryDto.setMeasureValue(dataMap.get(checkItem.getId()));
                    }
                    else {
                        dataHistoryDto.setMeasureValue(BigDecimal.ZERO.doubleValue());
                    }
                    dataHistoryDtoList.add(dataHistoryDto);
                }
            }
            else {
                for(TowerCheckItemVO checkItem : checkItemList) {
                    TowerDataHistoryVO dataHistoryDto = new TowerDataHistoryVO();
                    dataHistoryDto.setCheckItemName(checkItem.getCheckName());
                    dataHistoryDto.setMeasureValue(BigDecimal.ZERO.doubleValue());
                    dataHistoryDtoList.add(dataHistoryDto);
                }
            }
            lineDto.setDataList(dataHistoryDtoList);

            dataList.add(lineDto);
        }

        return ApiResponse.success(dataList);
    }

    @Override
    public ApiResponse<String> add(TowerDataHistorySearchVO towerDataHistorySearchVO) {
        TowerDataHistory towerDataHistory = new TowerDataHistory();
        BeanUtil.copyProperties(towerDataHistorySearchVO, towerDataHistory);
        towerDataHistory.setTyProjectCode("10101");//todo ContextUtil.getSessionUser().getTenantCode()
        towerDataHistory.setTyCreateTime(com.jxdinfo.hussar.cloud.module.example.tjjc.util.DateUtil.toLocalDateTime(new Date()));
        towerDataHistory.setTyCreateUserid("ContextUtil.getUserId()");//todo
        towerDataHistory.setTyCreateUserName("ContextUtil.getUserName()");//todo

        towerDataHistoryMapper.insert(towerDataHistory);

        return ApiResponse.success();
    }

    @Override
    public ApiResponse<String> updateTowerDataHistory(TowerDataHistorySearchVO towerDataHistorySearchVO) {
        TowerDataHistory towerDataHistoryOld = towerDataHistoryMapper.selectById(towerDataHistorySearchVO.getId());

        if(towerDataHistoryOld != null){
//            String[] ignoreProperties = {"tyCompanyName", "tyCompanyCode", "tyProjectName", "tyProjectCode", "tyCreateTime",
//                    "tyCreateUserid", "tyCreateUserName", "tyLastUpdateTime", "tyLastUpdateUserid", "tyLastUpdateUserName",
//                    "tyDeleteStatus", "tyOpterminal", "tyRemark"};
            BeanUtil.copyProperties(towerDataHistorySearchVO, towerDataHistoryOld);
            towerDataHistoryOld.setTyLastUpdateTime(com.jxdinfo.hussar.cloud.module.example.tjjc.util.DateUtil.toLocalDateTime(new Date()));
            towerDataHistoryOld.setTyLastUpdateUserid("ContextUtil.getUserId()");//todo
            towerDataHistoryOld.setTyLastUpdateUserName("ContextUtil.getUserName()");//todo

            towerDataHistoryMapper.updateById(towerDataHistoryOld);
        }

        return ApiResponse.success();
    }

    @Override
    public ApiResponse<String> deleteById(TowerDataHistorySearchVO towerDataHistorySearchVO) {
        TowerDataHistory towerDataHistoryOld = towerDataHistoryMapper.selectById(towerDataHistorySearchVO.getId());

        if(towerDataHistoryOld != null){
            //todo 原代码为逻辑删除
            towerDataHistoryMapper.deleteById(towerDataHistoryOld.getId());
        }

        return ApiResponse.success();
    }

    public static List<TowerCheckItemVO> towerCheckItemDtos() {
        List<TowerCheckItemVO> checkItemDtos = new ArrayList<>();
        List<String> checkNames = Arrays.asList("回转角度", "幅度", "风速", "速度", "吊重", "吊钩高度", "X轴倾斜角度", "Y轴倾斜角度", "力矩");
        for (int i = 0; i < 9; i++) {
            TowerCheckItemVO towerCheckItemDto = new TowerCheckItemVO();
            towerCheckItemDto.setCheckName(checkNames.get(i));
            towerCheckItemDto.setId(Convert.toStr(i+1));
            checkItemDtos.add(towerCheckItemDto);
        }
        return checkItemDtos;
    }
}
